package service

import (
	"github.com/gin-gonic/gin"
	"log"
	"mime/multipart"
	"my_music_server/common"
	"my_music_server/common/utils"
	"my_music_server/config"
	"my_music_server/model"
	"os"
)

type FileService struct {
}

// 定义一个通道,用来接收文件报错错误，配合select关键字获取通道内信息，自动关闭通道
var (
	errResult = make(chan error, 3)
)

func (f *FileService) Upload(songFile *multipart.FileHeader, lyricFile *multipart.FileHeader, coverFile *multipart.FileHeader, song *model.Song, c *gin.Context) string {
	if songFile == nil {
		//文件上传失败
		panic(common.ERROR_FILE_UPLOAD)
	}
	//检查上传目录是否存在
	exists, _ := utils.PathExists(config.AppicationConfig.File.Path)
	if !exists {
		//上传文件目录不存在
		_ = os.MkdirAll(config.AppicationConfig.File.Path, os.ModePerm)
		log.Printf("创建目录: %s\n", config.AppicationConfig.File.Path)
	}
	//上传到指定目录
	go func() {
		errResult <- c.SaveUploadedFile(songFile, config.AppicationConfig.File.Path+songFile.Filename)
	}()
	if lyricFile != nil {
		go func() {
			errResult <- c.SaveUploadedFile(songFile, config.AppicationConfig.File.Path+lyricFile.Filename)
		}()
	}
	if coverFile != nil {
		go func() {
			errResult <- c.SaveUploadedFile(songFile, config.AppicationConfig.File.Path+coverFile.Filename)
		}()
	}

label:
	for {
		select {
		case err := <-errResult:
			if err != nil {
				//文件保存失败
				panic(common.ERROR_FILE_SAVE)
			}
		default:
			break label
		}
	}

	return ""
}
